<?php
declare (strict_types=1);

namespace app\admin\controller\general;

use app\common\controller\BaseController;
use app\common\model\Attachment as AttachmentModel;
use app\common\library\storage\Storage;

class Attachment extends BaseController
{

    /**
     * @var AttachmentModel
     */
    protected $model;

    public function initialize()
    {
        parent::initialize();

        $this->model = new AttachmentModel;
    }


    public function del($ids = [])
    {
        if ($this->request->isDelete()) {
            $ids = $this->request->delete();
            if ($ids && is_array($ids)) {
                $pk = $this->model->getPk();
                $list = $this->model->where($pk, 'in', $ids)->select();
                $count = 0;
                foreach ($list as $k => $v) {
                    $storage = (new Storage())->driver($v['storage']);
                    $res = $storage->delete($v['path']);
                    if ($res) {
                        $count += $v->delete();
                    }
                }
                if ($count) {
                    return $this->success('删除成功');
                } else {
                    return $this->error(lang('No rows were deleted'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', 'id'));
        }
    }

}